/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package javamail.conn;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

/**
 *
 * @author sriram
 */
public class udpSocket {
    DatagramSocket socket = null;
    int port = 5600;
    public boolean error = false;
    private boolean debugEnabled = false;

    public udpSocket() {
        try {
            socket = new DatagramSocket();
            if(debugEnabled)
                System.out.println("UDP socket listening on port: " + socket.getLocalPort());
        } catch (SocketException e) {
            System.err.println("Could not create datagram socket." + e.getMessage());
            error = true;
        }
    }
    
    public udpSocket(int pPort) {
        try {
            // Start the listening on specified port, use default if 0 is passed
            if(pPort!=0)
                port = pPort;
            
            socket = new DatagramSocket(port);
            if(debugEnabled)
                System.out.println("UDP socket listening on port: " + socket.getLocalPort());
        } catch (SocketException e) {
            System.err.println("Could not create datagram socket." + e.getMessage());
            error = true;
        }
    }

    @Override
    protected void finalize() {
	if (socket != null) {
	    socket.close();
	    socket = null;
            if(debugEnabled)
                System.out.println("Closing datagram socket.");
	}
    }
    
    public DatagramPacket readPkt() {
        byte[] buf = new byte[65535];
	DatagramPacket packet;

        // receive request
        packet = new DatagramPacket(buf, buf.length);
        try {
            socket.receive(packet);
            if(packet.getLength()<=0)
                return null;
        } catch (IOException ignored) {  }
        //System.out.println(packet.getData().toString());
        return packet;
    }
    
    public void sendPkt(DatagramPacket pkt) {
        try {
            if(socket !=null)
                socket.send(pkt);
        } catch(IOException e) { }
    }
    public void setTimeout(int secs) {
        try {
            socket.setSoTimeout(secs);
        } catch(SocketException e) {}
    }
}
